﻿using Bot.Domain.SessionChat;

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Domain.Report
{
    public abstract class CalcuChatTimeService
    {
        private static long GetOnlyBotTotalTime(List<SessionChatDto> chats)
        {
            long result = 0;
            var list = chats.Where(c => c.ChatType == 1 && !string.IsNullOrEmpty(c.ChatContent)).ToList();
            foreach (var chat in list)
            {
                var messages = JsonConvert.DeserializeObject<List<SChatMessage>>(chat.ChatContent);
                var first = messages.Find(m => m.chatAction == EnumChatAction.enumChatbotJoinChat);
                var last = messages.Find(m => m.chatAction == EnumChatAction.enumSystemEndChat);
                if (last == null)
                {
                    last = messages.LastOrDefault();
                }
                if (last != null && first != null)
                {
                    result += last.time - first.time;
                }
            }
            return result;
        }
        private static long GetFromBotToAgentAgentTotalTime(List<SessionChatDto> chats)
        {
            long result = 0;
            var list = chats.Where(c => c.ChatType == 2 && !string.IsNullOrEmpty(c.ChatContent)).ToList();
            foreach (var chat in list)
            {
                var messages = JsonConvert.DeserializeObject<List<SChatMessage>>(chat.ChatContent);
                var first = messages.Find(m => m.chatAction == EnumChatAction.enumOperatorAcceptChat);
                var last = messages.Find(m => m.chatAction == EnumChatAction.enumSystemEndChat);
                if (first == null)
                {
                    continue;
                }
                if (last == null)
                {
                    last = messages.LastOrDefault();
                }
                if (last != null && first != null)
                {
                    result += last.time - first.time;
                }
            }
            return result;
        }
        private static long GetFromBotToAgentBotTotalTime(List<SessionChatDto> chats)
        {
            long result = 0;
            var list = chats.Where(c => c.ChatType == 2 && !string.IsNullOrEmpty(c.ChatContent)).ToList();
            foreach (var chat in list)
            {
                var messages = JsonConvert.DeserializeObject<List<SChatMessage>>(chat.ChatContent);
                var first = messages.Find(m => m.chatAction == EnumChatAction.enumChatbotJoinChat);
                var lastIndex = messages.FindIndex(m => m.chatAction == EnumChatAction.enumOperatorAcceptChat);
                if (lastIndex <= 0) break;
                var last = messages.ElementAtOrDefault(lastIndex - 1);
                if (last != null && first != null)
                {
                    result += last.time - first.time;
                }
            }
            return result;
        }
        private static long GetOnlyAgentTotalTime(List<SessionChatDto> chats)
        {
            long result = 0;
            var list = chats.Where(c => c.ChatType != 1 && c.ChatType != 2 && c.Operator1Id != Guid.Empty
                && !string.IsNullOrEmpty(c.ChatContent)).ToList();
            foreach (var chat in list)
            {
                try
                {
                    var messages = JsonConvert.DeserializeObject<List<SChatMessage>>(chat.ChatContent);
                    var first = messages.Find(m => m.chatAction == EnumChatAction.enumOperatorAcceptChat
                        || m.chatAction == EnumChatAction.enumOperatorAddInvitationText
                        || m.chatAction == EnumChatAction.enumOperatorInviteChat
                        || m.chatAction == EnumChatAction.enumOperatorInviteChatWithText
                        || m.chatAction == EnumChatAction.enumOperatorInviteChatWithText2);
                    if (first == null)
                    {
                        continue;
                    }
                    var last = messages.Find(m => m.chatAction == EnumChatAction.enumSystemEndChat);
                    if (last == null)
                    {
                        last = messages.LastOrDefault();
                    }
                    if (last != null && first != null)
                    {
                        result += last.time - first.time;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.Message+ "ChatContent="+chat.ChatContent);
                }
            }
            return result;
        }

        public static long GetAgentTotalTime(List<SessionChatDto> chats)
        {
            long result = GetOnlyAgentTotalTime(chats) + GetFromBotToAgentAgentTotalTime(chats);
            return result;
        }
        public static long GetBotTotalTime(List<SessionChatDto> chats)
        {
            long result = GetOnlyBotTotalTime(chats) + GetFromBotToAgentBotTotalTime(chats);
            return result;
        }
    }
    [DataContract]
    public class SChatMessage
    {
        //public int a; //_messageId;
        [DataMember(Name = "b")]
        public EnumChatAction chatAction; //_enumChatAction;
        [DataMember(Name = "c")]
        public string message; //_message;
        [DataMember(Name = "e")]
        public string senderName; //_sendName;
        //public string f; //_senderId;

        [DataMember(Name = "g")]
        public int time; //DateTime _time; utc时间转换成int
        //public bool h; //_translating;
        [DataMember(Name = "i")]
        public string translatedMessage; //_translatedMessage;
        [DataMember(Name = "j")]
        public string attachment; //Attachment:GUID;

    }
    public enum EnumChatAction
    {
        [EnumMember(Value = "systemEndChat")]
        enumSystemEndChat = 0,
        [EnumMember(Value = "systemPromoteOfflineMesage")]
        enumSystemPromoteOfflineMesage = 1,
        enumSystemEndVoiceChat = 2,             // - no use
        [EnumMember(Value = "visitorNotRespond")]
        enumSystemVisitorNotRespond = 3,
        [EnumMember(Value = "visitorNotRespondAndEndChat")]
        enumSystemVisitorNotRespondAndEndChat = 4,
        [EnumMember(Value = "systemStartChatbot")]
        enumSystemStartChatbot = 5,

        [EnumMember(Value = "visitorEndChatRequest")]
        enumVisitorEndChatRequest = 49,
        [EnumMember(Value = "visitorAddTextMessage")]
        enumVisitorAddTextMessage = 50,
        [EnumMember(Value = "visitorRequestChat")]
        enumVisitorRequestChat = 51,         //the corresponding message is the planid
        [EnumMember(Value = "visitorAcceptChat")]
        enumVisitorAcceptChat = 52,
        [EnumMember(Value = "visitorRefuseChat")]
        enumVisitorRefuseChat = 53,
        [EnumMember(Value = "visitorEndChat")]
        enumVisitorEndChat = 54,
        enumVisitorRequestVoice = 55,           // - no use
        enumVisitorAcceptVoice = 56,            // - no use
        enumVisitorRefuseVoice = 57,            // - no use
        enumVisitorEndVoice = 58,               // - no use

        [EnumMember(Value = "visitorSetName")]
        enumVisitorSetName = 59,
        [EnumMember(Value = "visitorSetEmail")]
        enumVisitorSetEmail = 60,
        [EnumMember(Value = "visitorSendFile")]
        enumVisitorSendFile = 61,
        [EnumMember(Value = "visitorSendImage")]
        enumVisitorSendImage = 62,
        [EnumMember(Value = "agentSendImage")]
        enumOperatorSendImage = 63,
        [EnumMember(Value = "agentSendImageStart")]
        enumOperatorSendImageStart = 64,


        enumVisitorHeartBeatForSite = 80,
        enumVisitorAutoInvitationShowed,
        enumVisitorRefuseInvitation,
        enumVisitorHeartBeatForChat,
        enumVisitorHeartBeatForPreChat,
        enumVisitorHeartBeatForOfflineMessage,

        enumVisitorAcceptCobrowse,
        enumVisitorRefuseCobrowse,
        enumVisitorCobrowseSource,
        enumVisitorCobrowseFullValueChange,
        enumVisitorCobrowseFullStyleChange,
        enumVisitorCobrowseDiffValueChange,
        enumVisitorCobrowseDiffStyleChange,

        [EnumMember(Value = "visitorTyping")]
        enumVisitorTyping,
        [EnumMember(Value = "visitorRequestChatWithQueue")]
        enumVisitorRequestChatWithQueue,

        enumOperatorLogin = 100,
        enumOperatorLogout,

        [EnumMember(Value = "agentSendText")]
        enumOperatorAddTextMessage,
        [EnumMember(Value = "agentInviteChat")]
        enumOperatorInviteChat,
        [EnumMember(Value = "agentAcceptChat")]
        enumOperatorAcceptChat, //104
        [EnumMember(Value = "agentRefuseChat")]
        enumOperatorRefuseChat,
        [EnumMember(Value = "agentEndChat")]
        enumOperatorEndChat,
        [EnumMember(Value = "agentJoinChat")]
        enumOperatorJoinChat,
        [EnumMember(Value = "agentTransferChat")]
        enumOperatorTransferChat,       //the corresponding message is the target operatorId 
        enumOperatorRequestVoice,           //no use
        enumOperatorAccepVoice,             //no use
        enumOperatorRefuseVoice,            //no use
        enumOperatorEndVoice,               //no use
        [EnumMember(Value = "agentSendUrl")]
        enumOperatorSendUrl,

        enumOperatorGetAllOperators,
        enumOperatorGetAllCurrentVisitors, //115
        enumOperatorGetNavigations,
        enumOperatorGetVisitorAllChatHistory,
        enumOperatorGetVisitorAllSessionHistory,
        enumOperatorSendPrivateMessageToOperator,
        enumOperatorSetPreChatForm,     //120 enumOperatorSetOperatorComment
        enumOperatorSetPreChatName,     //no use
        enumOperatorSetPreChatEmail,    //no use
        enumOperatorSetPreChatPhone,    //no use
        enumOperatorSetPreChatCompany,  //no use
        enumOperatorSetPreChatProductService,   //no use
        enumOperatorSetPreference,     //enumOperatorModifySoundSetting
        enumOperatorGetCannedMessages,
        enumOperatorGetCannedUrls,
        enumOperatorSendErrorMessageLog,
        enumOperatorGetVisitorAllChatAndOfflineMessageHistory, //130
        enumOperatorGetMessagesFromAllChats,

        enumOperatorRequestCobrowse,
        enumOperatorStopCobrowse,
        enumOperatorCobrowseDiffValueChange,

        enumOperatorGetAllCurrentVisitorsForMobile,
        enumOperatorGetVisitorDetails,
        enumOperatorGetVisitorContactHistoryDetails,

        enumOperatorGetDashboardMessage,
        [EnumMember(Value = "agentTyping")]
        enumOperatorTyping,
        [EnumMember(Value = "agentAttachNewTicket")]
        enumOperatorAttachNewTicket, //140
        [EnumMember(Value = "agentAttachExistingTicket")]
        enumOperatorAttachExistingTicket,

        [EnumMember(Value = "agentSendFile")]
        enumOperatorSendFile,
        enumOperatorSetStatus,
        enumOperatorMonitorChat, //144

        enumOperatorSetIphoneToken,
        enumOperatorSetIfNotifyIphone,
        enumOperatorSetTimeOut,

        enumOperatorGetDepartments,
        enumOperatorGetAutoInvitations,
        enumOperatorGetCodePlans,
        enumOperatorSetColumns,

        enumOperatorCaptureVisitor,
        enumOperatorBanVisitor,
        enumOperatorGetLastChat,
        enumOperatorSendEmail,

        enumOperatorGetSounds,
        [EnumMember(Value = "agentPromoteToUser")]
        enumOperatorPromoteToUser,
        [EnumMember(Value = "agentPromoteToContact")]
        enumOperatorPromoteToContact,
        enumOperatorInviteChatWithText,

        enumOperatorEnableModule,
        enumOperatorSetDashboardMessageNotShow,
        enumOperatorGetUserOrContactInfo,

        enumOperatorGetCustomerSegmentation,

        enumOperatorAutoLogin,
        enumOperatorSetAnotherOperatorStatus,
        enumOperatorSetNewAndroidToken,
        enumOperatorGetCurrentOperator,
        enumOperatorGetSiteDunningInfo,
        enumOperatorExtendChargeDate,

        enumOperatorCheckProductVersion = 200,
        enumOperatorGetDedicatedPlatformConfig = 201,
        enumOperatorSetTimezone = 202,
        enumOperatorGetVisitorHistoryNew = 203,
        //for visitor only, vm should ignore this action
        [EnumMember(Value = "visitorGetAgentName")]
        enumVisitorGetOperatorName = 204,
        [EnumMember(Value = "agentRecoverChat")]
        enumOperatorRecoverChat = 205,
        enumOperatorChangePassword = 206,
        enumOperatorSendRemoveIPBlockEmail = 207,

        enumOperatorEnableTranslate = 208,
        enumOperatorDisableTranslate = 209,
        enumOperatorDetectLanguage = 210,

        enumOperatorCheckG2MAccount = 211,
        enumOperatorCreateG2MMeeting = 212,
        enumOperatorCheckG2MBeforeSavePre = 213,
        enumOperatorGetUnfinishedWrapups = 214,
        enumOperatorSumitWrapup = 215,
        enumOperatorUseCannedMessage = 216,
        enumOperatorGetCustomAwayStatusList = 217,
        [EnumMember(Value = "agentTransferChatToDepartment")]
        enumOperatorTransferChatToDepartment = 218,
        [EnumMember(Value = "agentAcceptTransfer")]
        enumOperatorAcceptTransfer = 219,
        [EnumMember(Value = "agentRefuseTransfer")]
        enumOperatorRefuseTransfer = 220,

        [EnumMember(Value = "systemAgentIsBusy")]
        enumSystemOperatorIsBusy = 221,
        [EnumMember(Value = "systemGotoOfflineMessage")]
        enumSystemGotoOfflineMessage = 222,

        enumOperatorGetCustomVariables = 223,

        enumOperatorInviteChatWithText2 = 224, //用于窗口式的手动邀请
        [EnumMember(Value = "agentCancelManualInvitation")]
        enumOperatorCancelManualInvitation = 225,

        [EnumMember(Value = "agentAddInvitationText")]
        enumOperatorAddInvitationText = 226, //operator手动邀请时发送的邀请信息类型，用于VM端清除聊天窗口的上面一个聊天信息
        enumOperatorGetCustomerSegment = 227, //获取所有customer segments (GameTech 2期)
        enumOperatorSendJoinMePresenterLink = 228,

        enumOperatorGetSFIntegrationConfig = 229,
        enumOperatorGetSFObjectField = 230,
        enumOperatorCreateSFContactAndAttachCase = 231,
        enumOperatorEditSFContact = 232,
        enumOperatorCreateSFLead = 233,
        enumOperatorEditSFLead = 234,
        enumOperatorCreateSFCase = 235,
        enumOperatorAttachSFCaseToContact = 236,
        enumOperatorAttachSFTaskToLead = 237,
        enumOperatorLookupSFObject = 238,
        enumGetSFErrorMessageSFChatEnded = 239,

        enumAgentGetExtensions = 240,
        //新增的salesforce 接口
        enumOperatorCreateSFContactAndAttachTask = 241,
        enumOperatorAttachSFTaskToContact = 242,


        enumOperatorSendFileToOperator = 306,
        enumOperatorBeginSendImageToOperator = 307,
        enumOperatorEndSendImageToOperator = 308,

        [EnumMember(Value = "agentGetSecureForms")]
        enumOperatorGetSecureForms = 300,
        [EnumMember(Value = "agentRequestSecureForm")]
        enumOperatorRequestSecureForm = 301,
        [EnumMember(Value = "visitorGetSecureFormFailure")]
        enumVisitorGetSecureFormFailure = 302,
        [EnumMember(Value = "visitorSubmitSecureForm")]
        enumVisitorSubmitSecureForm = 303,
        [EnumMember(Value = "visitorCancelSecureForm")]
        enumVisitorCancelSecureForm = 304,
        [EnumMember(Value = "visitorCreditCardMasked")]
        enumVisitorCreditCardMasked = 305,

        enumOperatorGetVisitorWrapupHistory = 310,
        enumOperatorGetVisitorContanctWrapupDetails = 311,
        enumOperatorGetVisitorContactHistoryDetailsNew = 315,  //用于获取Json格式的content history detail接口

        [EnumMember(Value = "agentVideoChatRequest")]
        enumAgentVideoChatRequest = 320,    //sender - agent.Name, message - agent avatar url
        [EnumMember(Value = "agentVideoChatCancelRequest")]
        enumAgentVideoChatCancelRequest = 321,
        [EnumMember(Value = "agentVideoChatAccept")]
        enumAgentVideoChatAccept = 322,     //sender - agent.Name, message - agent avatar url
        [EnumMember(Value = "agentVideoChatRefuse")]
        enumAgentVideoChatRefuse = 323,
        [EnumMember(Value = "agentVideoChatStop")]
        enumAgentVideoChatStop = 324,

        [EnumMember(Value = "visitorVideoChatRequest")]
        enumVisitorVideoChatRequest = 325,
        [EnumMember(Value = "visitorVideoChatCancelRequest")]
        enumVisitorVideoChatCancelRequest = 326,
        [EnumMember(Value = "visitorVideoChatAccept")]
        enumVisitorVideoChatAccept = 327,
        [EnumMember(Value = "visitorVideoChatRefuse")]
        enumVisitorVideoChatRefuse = 328,
        [EnumMember(Value = "visitorVideoChatStop")]
        enumVisitorVideoChatStop = 329,

        [EnumMember(Value = "systemVideoChatNoAnswer")]
        enumSystemVideoChatNoAnswer = 330,
        [EnumMember(Value = "systemVideoChatEnd")]
        enumSystemVideoChatEnd = 331,

        [EnumMember(Value = "agentAudioChatRequest")]
        enumAgentAudioChatRequest = 332,    //sender - agent.Name, message - agent avatar url
        [EnumMember(Value = "agentAudioChatCancelRequest")]
        enumAgentAudioChatCancelRequest = 333,
        [EnumMember(Value = "agentAudioChatAccept")]
        enumAgentAudioChatAccept = 334,     //sender - agent.Name, message - agent avatar url
        [EnumMember(Value = "agentAudioChatRefuse")]
        enumAgentAudioChatRefuse = 335,
        [EnumMember(Value = "agentAudioChatStop")]
        enumAgentAudioChatStop = 336,

        [EnumMember(Value = "visitorAudioChatRequest")]
        enumVisitorAudioChatRequest = 337,
        [EnumMember(Value = "visitorAudioChatCancelRequest")]
        enumVisitorAudioChatCancelRequest = 338,
        [EnumMember(Value = "visitorAudioChatAccept")]
        enumVisitorAudioChatAccept = 339,
        [EnumMember(Value = "visitorAudioChatRefuse")]
        enumVisitorAudioChatRefuse = 340,
        [EnumMember(Value = "visitorAudioChatStop")]
        enumVisitorAudioChatStop = 341,

        [EnumMember(Value = "systemAudioChatNoAnswer")]
        enumSystemAudioChatNoAnswer = 342,
        [EnumMember(Value = "systemAudioChatEnd")]
        enumSystemAudioChatEnd = 343,

        [EnumMember(Value = "systemIfSupportWebrtc")]
        enumSystemIfSupportWebrtc = 344,

        //Chatbot-related.
        [EnumMember(Value = "chatbotRequestQuestionGuid")]
        enumChatbotReturnQuesionGuid = 360,
        [EnumMember(Value = "chatbotHighConfidenceAnswer")]
        enumChatbotHighConfidenceAnswer = 361,
        [EnumMember(Value = "chatbotPossibleAnswer")]
        enumChatbotPossibleAnswer = 362,
        [EnumMember(Value = "chatbotBadAnswer")]
        enumChatbotBadAnswer = 363,
        [EnumMember(Value = "chatbotSendGreetingMessage")]
        enumChatbotSendGreetingMessage = 364,
        // enumFromChatbotToAgent = 364,
        // enumChatbotServiceResponse = 365, //
        [EnumMember(Value = "chatbotSetAnswerIfHelpful")]
        enumChatbotSetAnswerIfHelpful = 366,
        [EnumMember(Value = "chatbotJoinChat")]
        enumChatbotJoinChat = 371,
        [EnumMember(Value = "chatbotNone")]
        enumChatbotNone = 372,
        [EnumMember(Value = "visitorCancelBotForm")]
        enumVisitorCancelBotForm = 373,
        [EnumMember(Value = "visitorSubmitBotForm")]
        enumVisitorSubmitBotForm = 374,
        [EnumMember(Value = "visitorConfirmBotForm")]
        enumVisitorConfirmBotForm = 375,
        [EnumMember(Value = "botSignIn")]
        enumBotSignIn = 376,
        [EnumMember(Value = "botForm")]
        enumBotForm = 377,
        [EnumMember(Value = "botConfirmForm")]
        enumBotConfirmForm = 378,
        [EnumMember(Value = "botPrompt")]
        enumBotPrompt = 379,
        [EnumMember(Value = "botRequestLocation")]
        enumBotRequestLocation = 380,
        [EnumMember(Value = "agentSendBotIntent")]
        enumAgentSendBotIntent = 381,

        [EnumMember(Value = "cobrowseRequest")]
        enumCobrowseRequest = 400,
        [EnumMember(Value = "cobrowseAccept")]
        enumCobrowseAccept,
        [EnumMember(Value = "cobrowseRefuse")]
        enumCobrowseRefuse,
        [EnumMember(Value = "cobrowseNoAnswer")]
        enumCobrowseNoAnswer,
        [EnumMember(Value = "cobrowseEnd")]
        enumCobrowseEnd,
        [EnumMember(Value = "cobrowseNotSupport")]
        enumCobrowseNotSupport,
        [EnumMember(Value = "cobrowseCancel")]
        enumCobrowseCancel,
        [EnumMember(Value = "cobrowseBrowserNotSupport")]
        enumCobrowseBrowserNotSupport,
        [EnumMember(Value = "cobrowseStart")]
        enumCobrowseStart,
        [EnumMember(Value = "cobrowseHttpNotSupport")]
        enumCobrowseHttpNotSupport,
        enumAgentGetGlanceLoginKey, // 410
    }
}
